//
//  MLHomeController.swift
//  weibo
//
//  Created by manmanlang on 16/6/22.
//  Copyright © 2016年 manmanlang. All rights reserved.
//

import UIKit
import AFNetworking

private let weiboCellId = "CellID"
class MLHomeController: MLBaseTableViewController {
    

    var weiboDataArray:[MLWeiboData] = [MLWeiboData]()
    private lazy var activityView :UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = ThemeColor
        return view
    }()
    let refresh = UIRefreshControl()

    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLogin {
            visitor?.setupInfo("关注一些人，回这里看看有什么惊喜", image: nil)
        }
        // 获取class 格式为 类名.self
        tableView.registerClass(MLWeiboCell.self, forCellReuseIdentifier: weiboCellId)
//        tableView.rowHeight = 200
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //给一个预估值
        tableView.estimatedRowHeight = 200
        ///设置tableView分割线样式
        tableView.separatorStyle = .None
        //刷新控件
        tableView.tableFooterView = activityView
        loadWeiboData(activityView.isAnimating())
        tableView.addSubview(refresh)
        refresh.addTarget(self, action: #selector(MLHomeController.refreshAction), forControlEvents: UIControlEvents.ValueChanged)
    }
    
    @objc private func refreshAction(){
        loadWeiboData(activityView.isAnimating())
    }
}



// MARK: - 首页微博数据
extension MLHomeController {
    
    func loadWeiboData(Pull: Bool){
        
        var sinceId: Int64 = 0
        var maxId: Int64 = 0
        if Pull {
            maxId = weiboDataArray.last?.id ?? 0
            //则返回ID小于或等于max_id的微博
            if maxId > 0 {
                maxId -= 1
            }
            
        }else {
            // 下拉刷新
            sinceId = weiboDataArray.first?.id ?? 0
        }
        
        MLNetworkTool.sharedNetworkTool.homeLoadWeiboData(sinceId, maxId: maxId, success: { (response) in
            //停止转动
            self.activityView.stopAnimating()
            self.refresh.endRefreshing()
            guard let result = response?["statuses"] as?[[String: AnyObject]] else {
                return
            }
            var tempArray:[MLWeiboData] = [MLWeiboData]()
            for dic in result {
                let weibo = MLWeiboData(dict: dic)
                tempArray.append(weibo)
            }
            //将数据返回  判断是上还是下拉
            if Pull {
                self.weiboDataArray = self.weiboDataArray + tempArray
            }else {
                self.weiboDataArray = tempArray + self.weiboDataArray
            }
            self.tableView.reloadData()
            }) { (error) in
                print("错误信息:\(error)")
        }
        
    }
}

///TableViewDelegate
extension MLHomeController {
    
    /**
     
     代理方法不执行的原因
     1.没有设置代理 --因为继承MLBaseTableViewController，所以不需要设置代理
     2.tableview的frame -- frame = (0 20; 375 647)
     3.代理方法return numberOfRows的返回值 -- 71
     4.数据源没有值 --有值，在35行
     
     */
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.weiboDataArray.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(weiboCellId, forIndexPath: indexPath) as! MLWeiboCell
        cell.weiboData = weiboDataArray[indexPath.row]
        return cell
    }
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: false)
    }
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if weiboDataArray.count == indexPath.row + 1 && !activityView.isAnimating() {
            print(indexPath.row)
            ///开启动画
            activityView.startAnimating()
            loadWeiboData(activityView.isAnimating())
        }
    }
}




